package com.google.code.sip.ucenter.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.code.sip.core.dao.Page;
import com.google.code.sip.ucenter.dao.mongo.AccountDaoImpl;
import com.google.code.sip.ucenter.dao.mongo.AccountLogDaoImpl;
import com.google.code.sip.ucenter.model.Account;
import com.google.code.sip.ucenter.model.AccountLog;
import com.google.code.sip.ucenter.model.User;
import com.google.code.sip.ucenter.service.AccountManager;

@Service("accountManager")
public class AccountManagerImpl implements AccountManager {

	@Autowired
	private AccountDaoImpl huoshowAccountDao;

	@Autowired
	private AccountLogDaoImpl huoshowAccountLogDao;

	// @Autowired
	// private UserDaoImpl userDao;

	@Override
	public long getBalance(User user) {

		// User user = userDao.get(userId);
		if (user != null) {
			Account huoshowAccount = huoshowAccountDao.getByUser(user);
			if (huoshowAccount != null) {
				return huoshowAccount.getBalance();
			} else {
				return 0;
			}
		} else {
			return 0;
		}

	}

	@Override
	public void updateAccount(User user, String type, String action,
			long amount, String remark) {
		// User user = userDao.get(userId);
		// 修改用户秀币值
		Account huoshowAccount = huoshowAccountDao.getByUser(user);
		if (huoshowAccount == null) {
			huoshowAccount = new Account();
			huoshowAccount.setUser(user);
			huoshowAccount.setBalance(0L);
		}
		long beforeBalance = huoshowAccount.getBalance();
		long afterBalance = 0;
		if (type.equals(AccountLog.TYPE_IN)) {
			afterBalance = beforeBalance + amount;
		}
		if (type.equals(AccountLog.TYPE_OUT)) {
			afterBalance = beforeBalance - amount;
		}
		huoshowAccount.setBalance(afterBalance);
		huoshowAccount.setLatedUpdatedDate(new Date());
		huoshowAccountDao.save(huoshowAccount);

		// 记录消费日志
		AccountLog huoshowAccountLog = new AccountLog();
		huoshowAccountLog.setAction(action);
		huoshowAccountLog.setAfterBalance(afterBalance);
		huoshowAccountLog.setBeforeBalance(beforeBalance);
		huoshowAccountLog.setAmount(amount);
		huoshowAccountLog.setComment(remark);
		huoshowAccountLog.setType(type);
		huoshowAccountLog.setAccount(huoshowAccount);
		huoshowAccountLog.setOperator(user);
		huoshowAccountLogDao.save(huoshowAccountLog);
	}

	@Override
	public Account getLogByUser(User user) {
		return huoshowAccountDao.getByProperty("user", user);

	}

	@Override
	public Page<Account> findLogByPage(Page<Account> page) {
		// TODO Auto-generated method stub
		return huoshowAccountDao.findByPage(page);
	}

}
